<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 17-4-12
 * Time: 10:34
 */

namespace frontend\widget;


use backend\models\Goods;
use frontend\models\GoodsCategory;
use yii\base\Widget;
use yii\helpers\ArrayHelper;
use yii\helpers\Url;

class GoodsListWidget extends Widget
{

    public $cate_id;
    public $allGoods=[];

    public function run()
    {
        $this->getAllGoods();
        $goodsHtml = '';
        foreach ($this->allGoods as $goods){
            $goods->logo= $goods->logoUrl();
            $goods = $goods->toArray();
            $imgsrc = $goods['logo'];
            $linkUrl = Url::to(['shop/goods','goods_id'=>$goods['id'],'goods_category_id'=>$this->cate_id]);
            $goodsHtml .='  <li><dl><dt><a href="'.$linkUrl.'"><img src="'.$imgsrc.'" alt="" /></a></dt>
                        <dd><a href="'.$linkUrl.'">'.$goods['name'].'</a></dd>
                        <dd><strong>'.$goods['shop_price'].'</strong></dd>
                        <dd><a href=""><em>已有10人评价</em></a></dd>
                    </dl>
                </li>';
        }

        return '<div class="goodslist mt10"><ul>'.$goodsHtml.'</ul></div>';

    }

    public function getAllGoods(){
        if($this->allGoods == null){
            //找到当前分类
            $current_cate=GoodsCategory::findOne(['id'=>$this->cate_id]);
            //找到当前分类和它的子分类
            $son_cates =GoodsCategory::find();
            $categorys = $son_cates->andWhere(['=','tree',$current_cate->tree])->andWhere(['>=','lft',$current_cate->lft])->andWhere(['<=','rgt',$current_cate->rgt])->asArray()->all();

            foreach ($categorys as $cate){
                //根据分类id获取商品信息
                $goods = Goods::find()->where(['goods_category_id'=>$cate['id']])->all();
                if(!empty($goods)){
    //                var_dump($goods);exit;
                    /** @var  $goods \backend\models\Goods */
                    //$this->allGoods[] = $goods;
                   $this->allGoods =ArrayHelper::merge($goods,$this->allGoods);
                }
            }
        }
            
        //var_dump($this->allGoods);exit;
    }


}